﻿namespace Microsoft.Samples.Kinect.SkeletonBasics
{
    using System.IO;
    using System.Windows;
    using System.Windows.Media;
    using Microsoft.Kinect;
    using System;
    using System.Collections.Generic;
    using System.Globalization;

    using System.Linq;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private KinectSensor sensor;        
        private bool connectedToKinectStudio = false;

        public MainWindow()
        {
            InitializeComponent();
        }
       
        private void WindowLoaded(object sender, RoutedEventArgs e)
        {
            // Look through all sensors and start the first connected one.
            // This requires that a Kinect is connected at the time of app startup.
            // To make your app robust against plug/unplug, 
            // it is recommended to use KinectSensorChooser provided in Microsoft.Kinect.Toolkit
            foreach (var potentialSensor in KinectSensor.KinectSensors)
            {
                if (potentialSensor.Status == KinectStatus.Connected)
                {
                    this.sensor = potentialSensor;
                    break;
                }
            }

            if (null != this.sensor)
            {
                // Turn on the skeleton stream to receive skeleton frames                
                this.sensor.ColorStream.Enable();

                // Add an event handler to be called whenever there is new color frame data
                
                this.sensor.ColorFrameReady += this.SensorColorFrameReady;

                // Start the sensor!
                try
                {
                    this.sensor.Start();
                }
                catch (IOException)
                {
                    this.sensor = null;
                }
            }

            if (null == this.sensor)
            {
                this.statusBarText.Text = Properties.Resources.NoKinectReady;
            }
        }
        private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
			if (null != this.sensor)
            {
                sensor.Stop();
            }
        }

        /// Output tracking information
        /// 
        //private TrackInfo tracks = new TrackInfo();        
                           
        // TimeStamp
        private bool initTimeStamp = false;
        private long upTimestamp = 0;
        private int frameDiff = 1000;
        private int frameCnt = 0;             
        long timestamp;

		/// <summary>
		///  Jpeg encoder
		/// </summary>
		System.Windows.Media.Imaging.JpegBitmapEncoder encoderJ = new System.Windows.Media.Imaging.JpegBitmapEncoder();

        private void SensorColorFrameReady(object sender, ColorImageFrameReadyEventArgs e)
        {
            if (!connectedToKinectStudio) return;

            using (ColorImageFrame colorFrame = e.OpenColorImageFrame())
            {                
                if ((colorFrame != null) && (colorFrame.PixelDataLength > 0) )
                {
                    timestamp = colorFrame.Timestamp;
                    if (timestamp <= 0) return;
                        
                    if (!initTimeStamp)
                    {
                        upTimestamp = timestamp + frameDiff;
                        initTimeStamp = true;
                    }

                    double difTimestamp = Convert.ToDouble(timestamp - upTimestamp);

                    if (difTimestamp <= 0) return;
                    
                    int difFrameNum = Convert.ToInt32(Math.Ceiling(difTimestamp / frameDiff));//int c = int;

                    if (difFrameNum > 1)
                    {
                        // add blank frames                            
                        for (int iAdd = 1; iAdd < difFrameNum; iAdd++)
                        {
                            //tracks.addFrame(frameCnt++, timestamp, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
							// save the image here gantian
							frameCnt++;
                            lb_frameNo.Content = frameCnt.ToString();
                        }
                    }                    

                    // update upTimestamp
                    upTimestamp += frameDiff * difFrameNum;
                    //MessageBox.Show(timestamp.ToString());
                }
            }
        }
      
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            if (connectedToKinectStudio)
            {
                button1.Content = "disconnected";
                connectedToKinectStudio = false;
            }
            else
            {
                button1.Content = "connected";
                connectedToKinectStudio = true;
            }

            
        }
    }
}